﻿using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;
using BDSync.Domains.Entities;
using DB.SchemaSync.Library.Models;
using DBSync.Tools;
using Newtonsoft.Json;

namespace BDSync.Domains.DBSnapShot
{

    /// <summary>
    /// 数快照导出对象
    /// </summary>
    public class DatabaseExport : DatabaseReserveObj
    {
        public DatabaseExport()
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">数据快照</param>
        /// <param name="dbName">数据库名称</param>
        public DatabaseExport(Database db,IDbConnection conn)
        { 
            DB = db;
            DBName = conn.Database;
        }

        /// <summary>
        /// 导出数据库 schema Json
        /// </summary>
        /// <param name="foldPath"></param>
        /// <returns></returns>
        public async Task<string> GenJsonFile(string foldPath)
        {
            var id = IdGeneratorHelper.Instance.GetId();
            var fileName = $"{DBName}-{id}.json";
            FileName = fileName;

            if (!Directory.Exists(foldPath))
            {
                Directory.CreateDirectory(foldPath);
            }

            var filePath = @$"{foldPath}\{FileName}";

            var jsonstr = JsonConvert.SerializeObject((DatabaseReserveObj)this);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            using (var fs = new StreamWriter(filePath))
            {
                await fs.WriteAsync(jsonstr);
                await fs.FlushAsync();
                fs.Close();
            }

            return FileName;
        }

    }
}